package com.taotao.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.TaotaoResult;
import com.taotao.common.TreeResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCatagoryService;
@Service
public class ContentCatagoryServiceImpl implements ContentCatagoryService {
	
	@Autowired
	private TbContentCategoryMapper contentCatagoryMapper;
	@Override
	public List<TreeResult> getContentCatogorys(Long parentId) {
		TbContentCategoryExample contentCategoryExample=new TbContentCategoryExample();
		Criteria criteria = contentCategoryExample.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbContentCategory> contentCatagorys = contentCatagoryMapper.selectByExample(contentCategoryExample);
		List<TreeResult> list=new ArrayList<>();
		for (TbContentCategory contentCategory : contentCatagorys) {
			TreeResult treeResult=new TreeResult();
			treeResult.setId(contentCategory.getId());
			treeResult.setText(contentCategory.getName());
			treeResult.setState(contentCategory.getIsParent()?"closed":"open");
			list.add(treeResult);
		}
		return list;
	}
	
	//添加内容分类
	@Override
	public TaotaoResult insertContentCatagory(Long parentId, String name) {
		TbContentCategory contentCategory=new TbContentCategory();
		contentCategory.setParentId(parentId);
		contentCategory.setName(name);
		contentCategory.setSortOrder(1);
		contentCategory.setStatus(1);
		contentCategory.setCreated(new Date());
		contentCategory.setUpdated(new Date());
		contentCategory.setIsParent(false);
		contentCatagoryMapper.insert(contentCategory);
		TbContentCategory selectByPrimaryKey = contentCatagoryMapper.selectByPrimaryKey(parentId);
		if(!selectByPrimaryKey.getIsParent()){
			selectByPrimaryKey.setIsParent(true);
			contentCatagoryMapper.updateByPrimaryKey(selectByPrimaryKey);
		}
		return TaotaoResult.ok(contentCategory);
	}

}
